<template>
  <view class="container">
    <view class="header">
      <text class="title">编辑收货地址</text>
      <text class="save-btn" @click="saveAddress">保存</text>
    </view>
    <view class="form-item">
      <label>姓名</label>
      <input v-model="formData.name" placeholder="请输入姓名" />
    </view>
    <view class="form-item">
      <label>电话</label>
      <input v-model="formData.phone" placeholder="请输入电话" />
    </view>
    <view class="form-item">
      <label>城市</label>
      <input v-model="formData.city" placeholder="请输入城市" />
    </view>
    <view class="form-item">
      <label>详细地址</label>
      <input v-model="formData.department" placeholder="请输入详细地址" />
    </view>
    <view class="form-item">
      <label>门牌号</label>
      <input v-model="formData.houseNumber" placeholder="请输入门牌号" />
    </view>
  </view>
</template>

<script>
import config from "@/config.js";

export default {
  data() {
    return {
      formData: {
        _id: '',
        name: '',
        phone: '',
        city: '',
        department: '',
        houseNumber: ''
      }
    };
  },
  onLoad(options) {
    if (options.id) {
      this.fetchAddressDetail(options.id);
    }
  },
  methods: {
    async fetchAddressDetail(addressId) {
      uni.showLoading({ title: '加载中...' });
      try {
        const res = await uni.request({
          url: `${config.api_host}data?_id=${addressId}`,
          method: 'GET'
        });

        const response = Array.isArray(res) ? res[1] : res;

        if (response && response.statusCode === 200) {
          const foundItem = response.data[0];
          if (foundItem) {
            this.formData = {
              _id: foundItem._id || foundItem.id,
              name: foundItem.name,
              phone: foundItem.phone,
              city: foundItem.city,
              department: foundItem.department,
              houseNumber: foundItem.houseNumber
            };
          } else {
            uni.showToast({ title: '未找到地址信息', icon: 'none' });
          }
        } else {
          uni.showToast({ 
            title: `获取地址失败: ${response.statusCode || '无响应'}`,
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取地址错误:', error);
        uni.showToast({ 
          title: '获取地址失败: ' + (error.message || '未知错误'),
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    async saveAddress() {
      // 表单验证
      if (!this.formData.name ||!this.formData.phone ||!this.formData.city || 
          !this.formData.department ||!this.formData.houseNumber) {
          uni.showToast({ title: '请填写完整信息', icon: 'none' });
          return;
      }

      uni.showLoading({ title: '保存中...' });
      try {
        // 先获取原数据
        const getRes = await uni.request({
          url: `${config.api_host}data?_id=${this.formData._id}`,
          method: 'GET'
        });

        const getResponse = Array.isArray(getRes) ? getRes[1] : getRes;

        if (getResponse && getResponse.statusCode === 200) {
          const originalData = getResponse.data[0];
          if (originalData) {
            // 合并新数据
            const updatedData = {
              ...originalData,
              ...this.formData
            };

            // 发起更新请求
            const updateRes = await uni.request({
              url: `${config.api_host}data/${originalData.id}`,
              method: 'PUT',
              data: updatedData,
              header: {
                'Content-Type': 'application/json'
              }
            });

            const updateResponse = Array.isArray(updateRes) ? updateRes[1] : updateRes;

            if (updateResponse.statusCode === 200) {
              uni.showToast({ title: '保存成功', icon:'success' });
              setTimeout(() => uni.navigateBack(), 1500);
            } else {
              throw new Error(updateResponse.data.message || '保存失败');
            }
          } else {
            throw new Error('未找到要更新的地址信息');
          }
        } else {
          throw new Error(`获取原数据失败: ${getResponse.statusCode || '无响应'}`);
        }
      } catch (error) {
        console.error('保存错误:', error);
        uni.showToast({ 
          title: error.message || '保存失败', 
          icon: 'none' 
        });
      } finally {
        uni.hideLoading();
      }
    }
  }
};
</script>

<style>
.container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.save-btn {
  color: #07c160;
  text-decoration: none;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
}

.form-item input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>